package com.example.shop_management.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop_management.entity.Admin;
import com.example.shop_management.service.impl.AdminServiceImpl;
import com.example.shop_management.utils.MD5Util;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminServiceImpl adminService;

    @GetMapping("findall")
    public List<Admin> findall() {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("aid");
        return adminService.list(queryWrapper);
    }


    @PostMapping("save")
    public boolean insert(@RequestBody Admin admin){
        admin.setPassword(MD5Util.getMD5(admin.getPassword()));
        return adminService.saveOrUpdate(admin);
    }

    @PostMapping("delete")
    public boolean delete(@RequestBody int id){
        return adminService.removeById(id);
    }

    @PostMapping("deleltebatch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return adminService.removeByIds(ids);
    }

    @GetMapping("selectbycondition")
    public List<Admin> selectByCondition(@RequestParam(defaultValue = "",required = false) String username,@RequestParam(defaultValue = "",required = false) String password){
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        if(!"".equals(username)){
            adminQueryWrapper.like("username",username);
        }
        if(!"".equals(password)){
            adminQueryWrapper.like("password",password);
        }
        return adminService.list(adminQueryWrapper);
    }

    @PostMapping("login")
    public Admin login(@RequestBody Admin admin, HttpSession session){
        if(StrUtil.isBlank(admin.getUsername())||StrUtil.isBlank(admin.getPassword())){
            return null;
        }
        Admin admin1 = adminService.login(admin);
        if(admin1!=null){
            session.setAttribute("admin",admin1);
        }
        return admin1;
    }


    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("admin");
    }


}

